package logx

import (
	"path"

	"gitee.com/zhaokangming/tiny-ticktok/config"

	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var log *zap.Logger

func InitLogger() {
	log = newLogger()
	zap.ReplaceGlobals(log)
}

// newLogger 初始化日志并创建实例
func newLogger() *zap.Logger {
	writeSyncer := getLogWriter()
	encoder := getEncoder()
	core := zapcore.NewCore(encoder, writeSyncer, zap.InfoLevel)
	return zap.New(core, zap.AddCaller())
}

// getEncoder 获取编码器
func getEncoder() zapcore.Encoder {
	encoderConf := zap.NewProductionEncoderConfig()
	encoderConf.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConf.EncodeLevel = zapcore.CapitalLevelEncoder
	return zapcore.NewConsoleEncoder(encoderConf)
}

// getLogWriter 获取写同步器
func getLogWriter() zapcore.WriteSyncer {
	fileName := path.Join(config.TikTok.Log.SavePath, config.TikTok.Log.FileName+config.TikTok.Log.FileExt)
	lumLogger := &lumberjack.Logger{
		Filename:   fileName,
		MaxSize:    config.TikTok.Log.MaxSize,
		MaxBackups: config.TikTok.Log.MaxBackUps,
		MaxAge:     config.TikTok.Log.MaxAge,
		Compress:   false,
	}
	return zapcore.AddSync(lumLogger)
}
